package com.visec.hdy.hadoop.analysis;

import java.text.SimpleDateFormat;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

/**
 * 时间分析实现类
 * 
 * @author hdy
 *
 * @param <V>
 */
public class TimeAnalysisImpl<V> extends DefaultAnalysisImpl<String, V, V> {
	private StringTimeHandle stringTimeHandle;

	public TimeAnalysisImpl(String key) {
		super(key);
		stringTimeHandle = new StringTimeHandle();
	}

	/**
	 * 时间处理类
	 * 
	 * @author hdy
	 *
	 */
	static class StringTimeHandle {
		private Pattern base;
		private Pattern all;
		private Pattern execption;
		private SimpleDateFormat format;
		final Logger l = Logger.getLogger(StringTimeHandle.class);

		StringTimeHandle() {
			base = Pattern
					.compile("20\\d{2}-[0-1]{1}\\d{1}-[0-3]{1}\\d{1} [0-2]{1}\\d{1}:[0-5]{1}\\d{1}:[0-5]{1}\\d{1}");
			execption = Pattern.compile(
					"20\\d{2}-[0-1]{1}\\d{1}-[0-3]{1}\\d{1} [0-2]{1}\\d{1}:[0-5]{1}\\d{1}:[0-5]{1}\\d{1}:\\d*");
			all = Pattern.compile(
					"20\\d{2}-[0-1]{1}\\d{1}-[0-3]{1}\\d{1} [0-2]{1}\\d{1}:[0-5]{1}\\d{1}:[0-5]{1}\\d{1}:\\d{3}");
			format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
		}

		String getTimeKey(String time) {
			try {
				if (all.matcher(time).matches())
					return String.valueOf(format.parse(time).getTime());
				if (base.matcher(time).matches()) {
					return String.valueOf(format.parse(time + ":000").getTime());
				}
				return String.valueOf(format.parse(modifyExecption(time)).getTime());
			} catch (Exception e) {
				l.error("", e);
				return null;
			}
		}

		String modifyExecption(String time) {
			String reTime = time;
			if (execption.matcher(time).matches()) {
				String substring = time.substring(time.lastIndexOf(':') + 1);
				switch (3 - substring.length()) {
				case 1:
					reTime += "0";
					break;
				case 2:
					reTime += "00";
					break;
				case 3:
					reTime += "000";
					break;
				default:
					reTime = time.substring(0, time.length() + 3 - substring.length());
					break;
				}
			}
			return reTime;
		}
	}

	@Override
	public com.visec.hdy.hadoop.standard.Analysis.Item<String, V> analyze(V value) {
		Object rf = reflexField(key, value);
		String key = null;
		if (rf instanceof java.util.Date) {
			key = String.valueOf(((java.util.Date) rf).getTime());
		}
		if (rf instanceof java.sql.Date) {
			key = String.valueOf(((java.sql.Date) rf).getTime());
		}
		if (rf instanceof String) {
			key = stringTimeHandle.getTimeKey((String) rf);
		}
		if (key == null)
			return null;
		return new Item<>(key, value);
	}

}
